home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / INFO / TSFAQP18.ZIP / FAQPAS2.TXT < prev    next >
Internet Message Format  |  1993-12-26  |  56KB

  1. From ts@uwasa.fi Sun Dec 26 00:00:00 1993
  2. Subject: FAQPAS2.TXT contents
  3.                                   Copyright (c) 1993 by Timo Salmi
  4.                                                All rights reserved
  5.  
  6. FAQPAS2.TXT More frequently (and not so frequently) asked Turbo
  7. Pascal questions with Timo's answers. The items are in no particular
  8. order.
  9.  
  10. You are free to quote brief passages from this file provided you
  11. clearly indicate the source with a proper acknowledgment.
  12.  
  13. Comments and corrections are solicited. But if you wish to have
  14. individual Turbo Pascal consultation, please rather post your
  15. questions to a suitable UseNet newsgroup like comp.lang.pascal. It
  16. is much more efficient than asking me by email. I'd like to help,
  17. but I am very pressed for time. I prefer to pick the questions I
  18. answer from the Usenet news. Thus I can answer publicly at one go if
  19. I happen to have an answer. Besides, newsgroups have a number of
  20. readers who might know a better or an alternative answer. Don't be
  21. discouraged, though, if you get a reply like this from me. I am
  22. always glad to hear from fellow Turbo Pascal users.
  23.  
  24. ..................................................................
  25. Prof. Timo Salmi      Co-moderator of comp.archives.msdos.announce
  26. Moderating at garbo.uwasa.fi anonymous FTP  archives  128.214.87.1
  27. Faculty of Accounting & Industrial Management; University of Vaasa
  28. Internet: ts@uwasa.fi   BBS +(358)-61-3170972; FIN-65101,  Finland
  29.  
  30. -------------------------------------------------------------------
  31. 31) How does one store, and then restore the original screen?
  32. 32) How can I convert a TPU unit of one TP version to another?
  33. 33) Which error is e.g. Runtime error 205, etc
  34. 34) Why can't I open read-only files? I get "File access denied".
  35. 35) How do I obtain high and low parts of a byte variable?
  36. 36) How can I set a hi-intensity color background in the text mode?
  37. 37) Where can I find a program to convert (Turbo) Pascal to C?
  38. 38) How can I read input without echoing to the screen?
  39. 39) How can I edit the readln input stream?
  40. 40) How can I write (brand) something into my executables?
  41. 41) What is wrong with my program? It hangs without a clear pattern?
  42. 42) How do I convert a decimal word into a hexadecimal string, etc?
  43. 43) How to determine the last drive?
  44. 44) How can I put a running clock into my Turbo Pascal program?
  45. 45) How to establish if a name refers to a directory or not?
  46. 46) How does one disable alt-ctrl-del?
  47. 47) How can I test whether a file exists?
  48. 48) What is the name of the current Turbo Pascal program?
  49. 49) How is the code for rebooting the PC written in Turbo Pascal?
  50. 50) How can I write inline code?
  51. 51) I am running out of memory when compiling my large program.
  52. 52) How do I avoid scrolling in the last column of the last row?
  53. 53) How can one hide (or unhide) a directory using a TP program?
  54. 54) How do I test whether a file is already open in a TP program?
  55. 55) How can I test and convert a numerical string into a real?
  56. 56) How can I reverse a TP .EXE or .TPU back into source code?
  57. 57) How can I calculate the difference between two points of time?
  58. 58) Is a program running stand-alone or from within the IDE?
  59. 59) Please explain Turbo Pascal memory addressing to me.
  60. 60) How do I obtain a bit or bits from a byte, a word or a longint?
  61. -------------------------------------------------------------------
  62.  
  63. From ts@uwasa.fi Sun Dec 26 00:00:31 1993
  64. Subject: Saving the screen
  65.  
  66. 31. *****
  67.  Q: How does one store, and then restore the original screen?
  68.  
  69.  A: Here is a simple outline for storing and restoring a text mode
  70. screen. Note that the code below is incomplete in a sense that it
  71. works for a color monitor only, because the monochrome screen
  72. address is $B000:$0000.
  73.    For storing and restoring the graphics screen see Ohlsen & Stoker
  74. (1989), Turbo Pascal Advanced Techniques, Que, pp 333-337.
  75.   uses Crt;
  76.   type ScreenType = array [1..4000] of byte;        (* 2 x 80 x 25 *)
  77.   var ColorScreen : ScreenType Absolute $B800:$0000;
  78.       SavedScreen : ScreenType;
  79.       posx, posy : byte;
  80.   begin
  81.     SavedScreen := ColorScreen;      (* Save the screen *)
  82.     posx := WhereX; posy := WhereY;  (* Save the cursor position *)
  83.     writeln ('A simple demo storing and restoring the color text screen');
  84.     writeln ('By Prof. Timo Salmi, ts@uwasa.fi');
  85.     writeln; write ('Press <-'''); readln;
  86.     ColorScreen := SavedScreen;   (* Restore the screen *)
  87.     GotoXY(posx,posy);            (* Go to the stored cursor position *)
  88.   end.
  89. If you would prefer not using the Crt unit, you can apply WHEREXFN,
  90. WHEREYFN, and GOATXY from TSUNTG.TPU from /pc/ts/tspa33*.zip.
  91. Likewise, if you wish to test for the monitor type, that is choose
  92. between $B800:$0000 and $B000:$0000 bases, you can use
  93.  MONOFN "Is it a monochrome video adapter"
  94. in the said units collection.
  95. --------------------------------------------------------------------
  96.  
  97. From ts@uwasa.fi Sun Dec 26 00:00:32 1993
  98. Subject: Converting TPUs
  99.  
  100. 32. *****
  101.  Q: How can I convert a TPU unit of one TP version to another?
  102.  
  103.  A: Forget it. In practical terms such a conversion is not on. The
  104. Turbo Pascal TPU units are strictly version dependent. If there were
  105. a working solution I assume we would have heard of it long since.
  106. The hacks that have been tried won't solve this dilemma. For all
  107. practical purposes you need the source code and the relevant
  108. compiler version.
  109.    You may nevertheless wish to ascertain for which version a TPU
  110. unit has been compiled. This is very simple. Just look at the first
  111. four character of a TPU file. The codes are
  112.  TPU0  for 4.0
  113.  TPU5  for 5.0
  114.  TPU6  for 5.5
  115.  TPU9  for 6.0
  116.  TPUQ  for 7.0 real mode
  117. But don't go editing these. It will not get you anywhere.
  118. --------------------------------------------------------------------
  119.  
  120. From ts@uwasa.fi Sun Dec 26 00:00:33 1993
  121. Subject: Finding about runtime errors
  122.  
  123. 33. *****
  124.  Q: Which error is e.g. Runtime error 205
  125.  
  126.  A: Basically this is a case of RTFM (read the f*ing manual). But it
  127. is very easy to find out even without resorting to the manual. Put
  128. temporarily the statement RunError (205); as the first statement of
  129. your program. Then run your program from the Turbo Pascal IDE, that
  130. is from within the TP editor. The description of the error will
  131. appear.
  132.    If you run a program from within a Turbo Pascal IDE, it is
  133. advisable to turn on the debug options on. You'll get both the error
  134. number and the description. Furthermore by pressing F1 after the
  135. error you get its description in a more verbal format.
  136.    One further trick is to put "uses TSERR"; (Include verbal
  137. run-time error messages) into your program. If you do that, the
  138. run-time errors will be given with a verbal description not just as
  139. a number. TSERR.TPU is part of my TPU collection /pc/ts/tspa*.zip.
  140. --------------------------------------------------------------------
  141.  
  142. From ts@uwasa.fi Sun Dec 26 00:00:34 1993
  143. Subject: Opening read-only files
  144.  
  145. 34. *****
  146.  Q: Why can't I open read-only files? I get "File access denied".
  147.  
  148.  A: The answer is rather simple, but it is not well displayed in the
  149. manuals. In order to read a read-only file you have to set the
  150. FileMode as 0 like below. Else you'll get runtime error 005 "File
  151. access denied".
  152.   var f      : text;          (* Can be any file type *)
  153.       savefm : byte;
  154.   begin
  155.     savefm := FileMode;       (* Save the current FileMode status *)
  156.     FileMode := 0;            (* The default is 2 *)
  157.     assign (f, 'readonly.txt');
  158.     reset (f);
  159.     { have your wicked ways }
  160.     close (f);
  161.     FileMode := savefm;       (* Restore the original FileMode *)
  162.   end.
  163. --------------------------------------------------------------------
  164.  
  165. From ts@uwasa.fi Sun Dec 26 00:00:35 1993
  166. Subject: Getting a nybble from a byte
  167.  
  168. 35. *****
  169.  Q: I have a variable of type BYTE and would like to extract two
  170. numbers from it. (The first 4 bits making up number A, the second 4
  171. bits making up number B).  How can I extract these two numbers?
  172.  
  173.  A: Ah, this questions bring back the good bad old days of the
  174. Commodore C64 programming when bit operations were rather a rule
  175. than an exception. Here is the solution.
  176.   function HIBYTEFN (x : byte) : byte;
  177.   begin
  178.     hibytefn := x Shr 4;           (* Shift right by four bits *)
  179.   end;
  180.   {}
  181.   function LOBYTEFN (x : byte) : byte;
  182.   begin
  183.     lobytefn := x and 15;          (* x and 00001111 *)
  184.   end;
  185. From Patrick Taylor (exuptr@exu.ericsson.se): Ah, leave it to Timo
  186. to come up with a different way! An other is (n div 16)
  187. (n mod 16).
  188.    Patrick is right.  But unless the compiler is optimized, the
  189. former produces more efficient code. Not that it really makes any
  190. practical difference whatsoever.
  191.    Of course the fastest code is produced using assembler as pointed
  192. out by Maarten Pennings (maarten@cs.ruu.nl) who provided the
  193. following inline example:
  194.   function high(b:byte):byte;
  195.     inline($58         { POP AX      | AH=?, AL=b       }
  196.           /$30/$e4     { XOR AH,AH   | AH=0, AL=b       }
  197.           /$b9/$04/$00 { MOV CX,0004 | AH=0, AL=b, CL=4 }
  198.           /$d3/$e8     { SHR AX,CL   | AX=b shr 4       }
  199.           );
  200.  
  201.  A2: Getting a word from a longint can alternatively be achieved
  202. without any calculations by using a kind of typecasting. Below is
  203. the code I have utilized in garbo.uwasa.fi:/pc/tspa*.zip.
  204.   (* Get the high-order word of the longint argument *)
  205.   function HIWORDFN (x : longint) : word;
  206.   type type1 = record
  207.                  low  : word;
  208.                  high : word;
  209.                end;
  210.   var m1 : type1 absolute x;
  211.   begin
  212.     hiwordfn := m1.high;
  213.   end;  (* hiwordfn *)
  214. --------------------------------------------------------------------
  215.  
  216. From ts@uwasa.fi Sun Dec 26 00:00:36 1993
  217. Subject: Setting hi-intensity background
  218.  
  219. 36. *****
  220.  Q: How can I set a hi-intensity color background in the text mode?
  221.  
  222.  A: As you should know, the you can test for a blinking text for
  223. example as follows.
  224.   uses Crt;
  225.   begin
  226.     TextColor (11 + 128);  (* or LightCyan + Blink *)
  227.     TextBackground (Blue);
  228.     writeln ('What''s the catch?');  (* An aside, note the '' pair *)
  229.   end.
  230. In the above, bit 7 (the 128) controls the blinking. If you have at
  231. least an EGA, you can alter the interpretation of the highest text
  232. color bit to denote a hi-intensity background, but then you lose the
  233. the blinking. The following piece of code disables blinking,
  234. enabling a hi-intensity background.
  235.   uses Dos;
  236.   var regs : registers;
  237.   begin
  238.     FillChar (regs, SizeOf(regs), 0); (* An initialization precaution *)
  239.     regs.ah := $10;                   (* Function $10 *)
  240.     regs.al := $03;                   (* Subfunction $03 *)
  241.     regs.bl := $00;
  242.     Intr ($10, regs);      (* ROM BIOS video driver interrupt *)
  243.   end.
  244. To enable blinking again, set regs.bl := $01; Any high-intensity
  245. background you may have currently on the screen, will instantly
  246. change into a blinking text a a low-intensity background.
  247.  
  248.  A2: The previous answer assumes at least an EGA. Otherwise ports
  249. must be accessed. This is both advanced and dangerous programming,
  250. because errors in handling posts can do real harm. Besides it is
  251. fair to require at least an EGA in writing modern programs, at least
  252. for non-laptops, and on the latter the colors don't really matter
  253. for CGA and below. Let's take a look, nevertheless, how this is done
  254. for a CGA. Note that this won't work an an EGA and beyond, not at
  255. least in my tests. For detecting the video adapter you have, see the
  256. DetectGraph procedure in you Turbo Pascal manual.
  257.    First we need some basics from MEMORY.LST in Ralf Brown's
  258. garbo.uwasa.fi:/pc/programming/inter38b.zip (or whatever version is
  259. current):
  260.  Format of BIOS Data Segment at segment 40h:
  261.   63h WORD Video CRT controller base address: color=03D4h, mono=03B4h
  262.   65h BYTE Video current setting of mode select register 03D8h/03B8h
  263. From David Jurgens's /pc/programming/helppc21.zip we see
  264.   3D0-3DF Color Graphics Monitor Adapter (ports 3D0-3DB are
  265.           write only, see 6845)
  266.   3D8 6845 Mode control register (CGA, EGA, VGA, except PCjr)
  267. From Darryl Friesen's (friesend@jester.usask.ca) in comp.lang.pascal
  268. we have, the following procedure, with my own added comments (* *).
  269.   procedure SetBlinkState (state : boolean);
  270.   var ModeRegPort : word;
  271.       ModeReg     : byte;
  272.   begin
  273.     Inline($FA); { CLI }           (* Interrupts off *)
  274.     ModeRegPort := MemW[$0040:$0063]+4;  (* Typically $03D4+4 = $03D8 *)
  275.     ModeReg := Mem[$0040:$0065];   (* Typically 1001 *)
  276.     if state then                  (* Bit 5 controls blink enable *)
  277.       ModeReg := ModeReg or $20    (* $20 = 00100000 (base2) *)
  278.     else
  279.       ModeReg := ModeReg and $DF;  (* $DF = 11011111 disable *)
  280.     Port[ModeRegPort] := ModeReg;  (* Typically $9 = 00001001 *)
  281.     Mem[$0040:$0065] := ModeReg;   (*       or $29 = 00101001 *)
  282.     Inline($FB) { STI }            (* Interrupts on *)
  283.   end;
  284. --------------------------------------------------------------------
  285.  
  286. From ts@uwasa.fi Sun Dec 26 00:00:37 1993
  287. Subject: Pascal to C
  288.  
  289. 37. *****
  290.  Q: Where can I find a program to convert (Turbo) Pascal to C?
  291.  
  292.  A: This is a relevant question, but I have placed elsewhere the
  293. tips on the "looking for a program" questions. Here are the
  294. pointers to further pointers :-). (The FAQ versions might have been
  295. updated since I wrote this.)
  296.  garbo.uwasa.fi:/pc/pd2/camfaq.zip
  297.  camfaq.zip comp.archives.msdos.(d/announce) FAQ (general finding)
  298.  :
  299.  garbo.uwasa.fi:/pc/pd2/tsfaqn39.zip
  300.  tsfaqn39.zip Questions from UseNet and Timo's answers
  301.  :
  302.  garbo.uwasa.fi:/pc/pd2/faquote.zip
  303.  faquote.zip Old information from tsfaq Frequently Asked Questions
  304. --------------------------------------------------------------------
  305.  
  306. From ts@uwasa.fi Sun Dec 26 00:00:38 1993
  307. Subject: Turning off the input echo
  308.  
  309. 38. *****
  310.  Q: How can I read input without echoing to the screen?
  311.  
  312.  A: It is fairly simple. Study this example source code, with the
  313. manual, if need be.
  314.   uses Crt;
  315.   var password : string;
  316.   {}
  317.   (* Read without echoing *)
  318.   procedure GETPASS (var s : string);
  319.   var key : integer;
  320.       ch : char;
  321.   begin
  322.     s := '';
  323.     repeat
  324.       ch := ReadKey; key := ord (ch);
  325.       case key of
  326.          0 : ch := ReadKey;  (* Discard two-character keys, like F1 *)
  327.         13 : exit;           (* Enter has been pressed *)
  328.         1..12,13..31,255 :;  (* Discard the special characters *)
  329.         else s := s + ch;
  330.       end;
  331.    until false;
  332.   end;  (* getpass *)
  333.   {}
  334.   (* The main program *)
  335.   begin
  336.     write ('Password: ');
  337.     GETPASS (password);
  338.     writeln;
  339.     writeln (password);
  340.   end.
  341.   {}
  342. If you wish to be able to edit the input stream, like having the
  343. BackSpace functional, that is more complicated, and is left as an
  344. exercise after these basics. A hint: 8 : Delete (s, Length(s), 1);
  345. --------------------------------------------------------------------
  346.  
  347. From ts@uwasa.fi Sun Dec 26 00:00:39 1993
  348. Subject: Input line-editing
  349.  
  350. 39. *****
  351.  Q: How can I edit the readln input stream?
  352.  
  353.  A: In practice, if you wish to use anything beyond simple the
  354. BackSpace deleting, you'll have to build your own line editing
  355. routines expanding on the code in the previous item. It is quite a
  356. task, and you can alternatively find the preprogrammed routines in
  357. my Turbo Pascal units tspa33*.zip (or whatever version number is
  358. current).
  359.  EDRDEBLN Editable Readln with ctrl-c, break trapping, pre-fill etc
  360.  EDRDEFLN Editable Readln with recall, pre-fill, and insert toggle
  361.  EDRDLN   Readln with line-editing potential (the simplest)
  362.  EDREABLN Edreadln with ctrl-c and break trapping
  363.  EDREADLN Editable Readln with recall, and insert toggle
  364. --------------------------------------------------------------------
  365.  
  366. From ts@uwasa.fi Sun Dec 26 00:00:40 1993
  367. Subject: Executable branding
  368.  
  369. 40. *****
  370.  Q: How can I write (brand) something into my executables?
  371.     Here is the actual question that led me to writing this item: 'I
  372.     am very interested in the .EXE "branding" techniques you use in
  373.     your TSUNTI unit. Would it be possible to get hold of the source
  374.     code for that unit, as it would save me from having to re-invent
  375.     the wheel?'
  376.  
  377.  A: What you are referring to is
  378.  BRANDEXE Store information within your program's .exe file (MsDos 3.0+)
  379.  CHKSUMFN Checksum selftest to detect any tampering (MsDos 3.0+)
  380.  USECOUNT Get the number of times the program has been used
  381. Sorry no, I don't want to distribute my /pc/turbopas/tspa33*.zip
  382. source codes.  Besides they would be less useful to you than you may
  383. think because internally my programs are in Finnish, comments,
  384. variable and procedure names, and all. But I can hopefully help you
  385. by giving a reference to a similar code.  Please see Ohlsen &
  386. Stoker, Turbo Pascal Advanced Techniques, Que, 1989, p. 420.
  387. --------------------------------------------------------------------
  388.  
  389. From ts@uwasa.fi Sun Dec 26 00:00:41 1993
  390. Subject: Elusive, inconsistent errors
  391.  
  392. 41. *****
  393.  Q: What is wrong with my program? It hangs without a clear pattern?
  394.  
  395.  A: With experience one learns that some programming errors are very
  396. elusive. I have many times seen users declaring that they have found
  397. a bug in Turbo Pascal, but in the overwhelming majority of cases it
  398. still is just a programming error, which just is more difficult to
  399. find than the more clear-cut cases. When you have symptoms like your
  400. program crashing from within the IDE, but working seemingly all
  401. right when called as stand-alone, or something equally strange, you
  402. might have one of the following problems.
  403. - A variable or some variables in your code are uninitialized thus
  404.   getting random values, which differ depending on your environment.
  405. - Your indexes are overflowing. Set on the range check {$R+}
  406.   directive for testing.
  407. - An error in the pointer logic.
  408. Normal debugging does not necessarily help in locating these errors
  409. because one is easily led to debugging the wrong parts of one's
  410. program. Especially the latter two reasons can cause errors which
  411. seemingly have nothing to do with the actual cause. This results
  412. from the fact that indexing and pointer errors can overwrite parts
  413. of memory causing strange quirks in your program. If you have used
  414. indexing with {$R-} or if you use pointer operations, sooner or
  415. later you are bound to have these problems in developing your
  416. applications.
  417.    See Edward Mitchell (1993), Borland Pascal Developer's Guide,
  418. 275-288 for common programming errors and especially the information
  419. on memory clobbering, in a useful chapter on debugging Turbo Pascal
  420. programs. You might also take a look at your Turbo Pascal User's
  421. Guide. At least version 7.0 has an instructive general
  422. categorization of errors on pages 76-77.
  423. --------------------------------------------------------------------
  424.  
  425. From ts@uwasa.fi Sun Dec 26 00:00:42 1993
  426. Subject: Converting the number base
  427.  
  428. 42. *****
  429.  Q: How do I convert a decimal word into a hexadecimal string, etc?
  430.  
  431.  A: Here is one possibility
  432.   function HEXFN (decimal : word) : string;
  433.   const hexDigit : array [0..15] of char = '0123456789ABCDEF';
  434.   begin
  435.     hexfn := hexDigit[(decimal shr 12)]
  436.           + hexDigit[(decimal shr 8) and $0F]
  437.           + hexDigit[(decimal shr 4) and $0F]
  438.           + hexDigit[(decimal and $0F)];
  439.   end;  (* hexfn *)
  440. Here is another conversion example (from longint to binary string)
  441.   function LBINFN (decimal : longint) : string;
  442.   const BinDigit : array [0..1] of char = '01';
  443.   var i     : byte;
  444.       binar : string;
  445.   begin
  446.     FillChar (binar, SizeOf(binar), ' ');
  447.     binar[0] := chr(32);
  448.     for i := 0 to 31 do
  449.       binar[32-i] := BinDigit[(decimal shr i) and 1];
  450.     lbinfn := binar;
  451.   end;  (* lbinfn *)
  452. For a full set of conversions, both from and to decimal, apply
  453. TSUTNTB.TPU from garbo.uwasa.fi:/pc/ts/tspa*.zip.
  454. --------------------------------------------------------------------
  455.  
  456. From ts@uwasa.fi Sun Dec 26 00:00:43 1993
  457. Subject: Identifying the last drive
  458.  
  459. 43. *****
  460.  Q: How to determine the last drive?
  461.  
  462.  A: One way of doing that is utilizing the information in DPB, that
  463. is the Drive Parameter Block, but that is rather complicated, so you
  464. can find that without source code in garbo.uwasa.fi:/pc/ts/tspa*.zip
  465. in the TSUNTH unit.
  466.  Another way is using interrrupt 21H, function 36H to detect if a
  467. drive exists starting from the first drive letter. The code is given
  468. below. The disadvantage of this method is that it does not
  469. distinguish between real and substituted drives.
  470.   uses Dos;
  471.   function LASTDFN : char;  (* Detect last harddisk letter *)
  472.   var regs : registers;
  473.       i    : byte;
  474.   begin
  475.     i := 2;
  476.     repeat
  477.       Inc(i);
  478.       FillChar (regs, SizeOf(regs), 0);
  479.       regs.ah := $36;
  480.       regs.dl := i;
  481.       MsDos(regs);
  482.     until (regs.ax = $FFFF);
  483.     lastdfn := chr(i+63);
  484.   end;  (* lastdfn *)
  485. --------------------------------------------------------------------
  486.  
  487. From ts@uwasa.fi Sun Dec 26 00:00:44 1993
  488. Subject: Clock display in a TP program
  489.  
  490. 44. *****
  491.  Q: How can I put a running clock into my Turbo Pascal program?
  492.  
  493.  A: We are not speaking of a stand-alone TSR-clock (which is a
  494. different task), but considering a clock that continuously displays
  495. the time in some part of the output screen of your Turbo Pascal
  496. program.
  497.     You might first want to read the earlier items about ReadKey
  498. usages if you are not familiar with it (you probably are, because
  499. you would not pose this advanced question if you were a novice). The
  500. items are the unlikely "How do I disable or capture the break key in
  501. Turbo Pascal?" and "How can I read input without echoing to the
  502. screen?"
  503.    The general idea is to make the body of the program a repeat
  504. until loop using ReadKey for input and updating the clock display
  505. at suitable junctions within the loop. The scheme is thus something
  506. like the following.
  507.   procedure showtime;
  508.     begin
  509.       { if the second has changed, write the time }
  510.     end;
  511.   :
  512.   repeat
  513.     { do whatever }
  514.     showtime;
  515.     if KeyPressed then
  516.       case ReadKey of
  517.         { whatever }
  518.         { exit rules }
  519.       end;
  520.     showtime;
  521.     :
  522.     showtime;
  523.   until false;
  524.    One trick of the trade is that you must not update your clock
  525. each time the clock routine is encountered. You should test if the
  526. second has changed, and update only then. Else you are liable to get
  527. an annoying flicker in your clock.
  528. --------------------------------------------------------------------
  529.  
  530. From ts@uwasa.fi Sun Dec 26 00:00:45 1993
  531. Subject: Is a name a directory
  532.  
  533. 45. *****
  534.  Q: How to establish if a name refers to a directory or not?
  535.  
  536.  A: This question has turned out a bit more complicated than I first
  537. thought. There are several methods, each with some catch. The first
  538. is trying to open the name as a file and observing the IOResult. The
  539. ISDIRFN function in garbo.uwasa.fi:/pc/ts/tspa*.zip TPU unit
  540. TSUNTJ.TPU is based on this method. Unfortunately it is not always
  541. stable. I have been reported problems in connection with DRDOS by
  542. Richard Breuer (ricki@pool.informatik.rwth-aachen.de) who has
  543. tested these routines.
  544.   The second method (ISDIR2FN) is based on the fact that the file
  545. NUL exists in a directory if the directory exists.
  546.   The thrid method (ISDIR3FN) is a brute force method. It is given
  547. below, since it is quite an instructive little exercise of Turbo
  548. Pascal programming.
  549.   (* Search recursively through a drive's directories.
  550.      Auxiliary, recursive procedure for ISDIR3FN *)
  551.   procedure SEARCHDR (Path, FileSpec : string;
  552.                       name           : string;
  553.                       var found      : boolean);
  554.   var FileInfo : SearchRec;
  555.   begin
  556.     FindFirst (Path + '*.*', Directory, FileInfo);
  557.     while DosError = 0 do
  558.       begin
  559.         if ((FileInfo.Attr and Directory) > 0) and
  560.             (FileInfo.Name <> '.') and
  561.             (FileInfo.Name <> '..') then
  562.               begin
  563.                 SEARCHDR (Path + FileInfo.Name + '\',
  564.                           FileSpec,
  565.                           name,
  566.                           found);
  567.                 if Path + FileInfo.Name + '\' = name then
  568.                   found := true;
  569.               end;
  570.         FindNext (FileInfo);
  571.       end; {while}
  572.   end;  (* searchdr *)
  573.  
  574.   (* Does a name refer to a directory *)
  575.   function ISDIR3FN (name : string) : boolean;
  576.   var drive : char;
  577.       found : boolean;
  578.   begin
  579.     {... Default value ...}
  580.     isdir3fn := false;
  581.     {... Discard empty names ...}
  582.     if name = '' then exit;
  583.     {... Expand into a fully qualified name, makes it uppercase ...}
  584.     name := FExpand (name);
  585.     if name[Length(name)] <> '\' then name := name + '\';
  586.     {... Extract the drive letter from the name ...}
  587.     drive := UpCase (name[1]);
  588.     {... Check first for the root ...}
  589.     if drive + ':\' = name then
  590.       begin isdir3fn := true; exit; end;
  591.     {... Check the rest of the directories recursively ...}
  592.     found := false;
  593.     SEARCHDR (drive + ':\', '*.*', name, found);
  594.     isdir3fn := found;
  595.   end;  (* isdir3fn *)
  596. --------------------------------------------------------------------
  597.  
  598. From ts@uwasa.fi Sun Dec 26 00:00:46 1993
  599. Subject: Disabling alt-ctrl-del
  600.  
  601. 46. *****
  602.  Q: How does one disable alt-ctrl-del?
  603.  
  604.  A: I can only give a pointer to source code. Take a look at the
  605. code by Mikko Hanninen in garbo.uwasa.fi:/pc/turbopas/cadthf10.zip.
  606.    I have utilized alt-ctrl-del disabling at least in one of my own
  607. programs (PESTIKID.EXE). The code is not available, but the general
  608. idea is replacing the old keyboard interrupt ($09) with a handler of
  609. one's own. If the handler detects alt-ctrl-del, the keyboard is
  610. reset, else the handler is chained back to the original interrupt.
  611. The chaining requires a rather complicated inline procedure provided
  612. in TurboPower Software's kit. An additional complication is that the
  613. del keypress must be intercepted already at the relevant port $60,
  614. and the alt and ctrl status must be tested, so that the rebooting
  615. will not be invoked. Resetting the keyboard requires accessing the
  616. $20 and $61 ports.
  617. --------------------------------------------------------------------
  618.  
  619. From ts@uwasa.fi Sun Dec 26 00:00:47 1993
  620. Subject: Does a file exist
  621.  
  622. 47. *****
  623.  Q: How can I test whether a file exists?
  624.  
  625.  A: There are several alternatives. Here is the most common with
  626. example code. It recognizes also read-only, hidden and system files.
  627.   function FILEXIST (name : string) : boolean;
  628.   var fm : byte;
  629.       f  : file;
  630.       b  : boolean;
  631.   begin
  632.     fm := FileMode;
  633.     FileMode := 0;
  634.     assign (f, name);
  635.     {$I-} reset(f); {$I+}
  636.     b := IOResult = 0;
  637.     if b then close(f);
  638.     filexist := b;
  639.     FileMode := fm;
  640.   end;
  641.  
  642. A second alternative is
  643.   Uses Dos;
  644.   function FILEXIST (name : string) : boolean;
  645.   var f  : file;
  646.       a  : word;
  647.   begin
  648.     assign (f, name);
  649.     GetFAttr (f, a);
  650.     filexist := false;
  651.     if DosError = 0 then
  652.       if ((a and Directory) = 0) and ((a and VolumeId) = 0) then
  653.         filexist := true;
  654.   end;
  655.  
  656. A third alternative is
  657.   Uses Dos;
  658.   function FILEXIST (name : PathStr) : boolean;
  659.   begin
  660.     filexist := FSearch (name, '') <> '';
  661.   end;
  662.  
  663. A fourth alternative is the following. Be careful with this option,
  664. since it works a bit differently from the others. It accepts wild
  665. cards. Thus, for example FILEXIST('c:\autoexec.*') would be TRUE in
  666. this method, while FALSE in all the above.
  667.   Uses Dos;
  668.   function FILEXIST (name : string) : boolean;
  669.   var f : SearchRec;
  670.   begin
  671.     filexist := false;
  672.     FindFirst (name, AnyFile, f);
  673.     if DosError = 0 then
  674.       if (f.attr <> Directory) and (f.attr <> VolumeId) then
  675.         filexist := true;
  676.   end;
  677. A good variation from KDT@newton.national-physical-lab.co.uk of this
  678. theme, disallowing wildcards:
  679.   function file_exists (fname :string) :boolean;
  680.   var f :searchrec;
  681.   begin
  682.     findfirst (fname, anyfile - directory - volumeid, f);
  683.     file_exists := (doserror + pos('*',fname) + pos('?',fname) = 0);
  684.   end;
  685.  
  686. --------------------------------------------------------------------
  687.  
  688. From ts@uwasa.fi Sun Dec 26 00:00:48 1993
  689. Subject: The current program name
  690.  
  691. 48. *****
  692.  Q: What is the name of the current Turbo Pascal program?
  693.  
  694.  A: The name of the currently executing Turbo Pascal program is in
  695. ParamStr(0).
  696.    This was introduced in TP version 5.0, and as far as I recall at
  697. least MsDos version 3.0 is required. For TP 4.0 you can use
  698. "ParamStr0 The name of the program" from TSUNT45 in garbo.uwasa.fi:
  699. /pc/ts/tspa3340.zip (or whatever the version number is the latest).
  700.    It is advisable to put the value into a string variable at be
  701. beginning of the program before eny I/O takes place. Thus you might
  702. wish to use:
  703.   var progname : string;
  704.   begin  { the main program }
  705.     progname := ParamStr(0);
  706.     :
  707. A bonus of this method is that you can access the individual
  708. characters of progname (e.g. progname[1] for the drive) while that
  709. is not possible to do for the ParamStr keyword.
  710. --------------------------------------------------------------------
  711.  
  712. From ts@uwasa.fi Sun Dec 26 00:00:49 1993
  713. Subject: How can a program reboot my PC?
  714.  
  715. 49. *****
  716.  Q: How is the code for rebooting the PC written in Turbo Pascal?
  717.  
  718.  A: This item draws from the information and the C-code example in
  719. Stan Brown's comp.os.msdos.programmer FAQ, garbo.uwasa.fi:
  720. /pc/doc-net/faqp9317.zip (at the time of writing this), from
  721. memory.lst and interrup.b in /pc/programming/inter38b.zip, and from
  722. /pc/programming/helppc21.zip. The Turbo Pascal code is my adaptation
  723. of the C-code. It is not a one-to-one replica.
  724.    The usually advocated warm-boot method is storing $1234 in the
  725. word at $0040:$0072 and jumping to address $FFFF:$0000. The problem
  726. with this approach is that files must first be closed, potential
  727. caches flushed. This is how to do this
  728.   procedure REBOOT;
  729.   label next;
  730.   var regs  : registers;
  731.       i     : byte;
  732.       ticks : longint;
  733.   begin
  734.     {... "press" alt-ctrl ...}
  735.     mem[$0040:$0017] := mem[$0040:$0017] or $0C;  { 00001100 }
  736.     {... "press" del, try a few times ...}
  737.     for i := 1 to 10 do
  738.       begin
  739.         FillChar (regs, sizeOf(regs), 0);  { initialize }
  740.         regs.ah := $4F;  { service number }
  741.         regs.al := $53;  { del key's scan code }
  742.         regs.flags := FCarry;  { "sentinel for ignoring key" }
  743.         Intr ($15, regs);
  744.         {... check if the del key registered, if not retry ...}
  745.         if regs.flags and Fcarry > 0 then goto next;
  746.         {... waste some time, watch out for midnight ...}
  747.         ticks := MemL [$0040:$006C];
  748.         repeat until (MemL[$0040:$006C] - ticks > 3) or
  749.                      (MemL[$0040:$006C] - ticks < 0)
  750.     end; {for}
  751.     exit;
  752.   next:
  753.     {... disk reset: writes all modified disk buffers to disk ...}
  754.     FillChar (regs, sizeOf(regs), 0);
  755.     regs.ah := $0D;
  756.     MsDos (regs);
  757.     {... set post-reset flag, use $0000 instead of $1234 for coldboot ...}
  758.     memW[$0040:$0072] := $1234;
  759.     {... jump to $FFFF:0000 BIOS reset ...}
  760.     Inline($EA/$00/$00/$FF/$FF);
  761.   end;  (* reboot *)
  762. One slight problem with this approach is that the keyboard intercept
  763. interrupt $15 service $4F requires at least an AT according to
  764. inter38b.zip. A simple test based on "FFFF:E byte ROM machine id"
  765. (the previous definition is from helppc21.zip) is:
  766.   function ISATFN : boolean;
  767.   begin
  768.      case Mem[$F000:$FFFE] of
  769.        $FC, $FA, $F8 : isatfn := true;
  770.        else isatfn := false;
  771.      end; {case}
  772.   end;  (* isatfn *)
  773. For a more comprehensive test use CPUFN "Get the type of the
  774. processor chip" from TSUNTH in garbo.uwasa.fi:/pc/ts/tspa*.zip or
  775. see the TP + ASM code in Michael Ticher (1992), PC Intern System
  776. Programming, pp. 725-727.
  777.    An addition by Per Bergland (d6caps@dtek.chalmers.se): I recently
  778. downloaded the FAQ for this newsgroup, and studied the code for
  779. rebooting a PC. The problem with that code (calling FFFF:0000) is
  780. that it will not work in protected mode programs such as those
  781. compiled for Windows or BP7 DPMI, or even in a DOS program run in a
  782. Windows DOS session. The solution provided has been tested on
  783. various COMPAQ PC:s, but I think it will work on any AT-class
  784. machine. It involves using the 8042 keyboard controller chip output
  785. pin 0, which is physically connected to the reset pin of the CPU.
  786. There is unfortunately no way to perform a "warm" reboot this way,
  787. and the warnings about disk caches etc apply to this code, too (see
  788. FAQ). The code is written in BP7 assembly lingo, because that's what
  789. I normally write code in, but anyone could rewrite it in C or high
  790. level Pascal.
  791.   UNIT Reboot;
  792.   INTERFACE
  793.     procedure DoReboot;
  794.   IMPLEMENTATION
  795.     procedure DoReboot;assembler;
  796.     asm
  797.       cli
  798.   @@WaitOutReady:       { Busy-wait until 8042 is ready for new command}
  799.       in al,64h         { read 8042 status byte}
  800.       test al,00000010b { Bit 1 of status indicates input buffer full }
  801.       jnz @@WaitOutReady
  802.       mov al,0FEh       { Pulse "reset" = 8042 pin 0 }
  803.       out 64h,al
  804.       { The PC will reboot now }
  805.     end;
  806.   END.
  807. --------------------------------------------------------------------
  808.  
  809. From ts@uwasa.fi Sun Dec 26 00:00:50 1993
  810. Subject: Writing inline code
  811.  
  812. 50. *****
  813.  Q: How can I write inline code?
  814.  
  815.  A: In Turbo Pascal versions prior 6.0 assembler code could not be
  816. directly included in the code. Instead one had to assemble the code
  817. into inline statements. Consider the task of rebooting the PC
  818. (without disk closing and cache flushing).  The assemble code for
  819. this is
  820.   mov ax,40
  821.   mov ds,ax
  822.   mov wo [72],1234
  823.   jmp FFFF:0000
  824. To assemble this code into an inline statement write the following
  825. file calling it e.g. debug.in.  The empty line is important.
  826.   .... begin debug.in, cut here ....
  827.   a 100
  828.   mov ax,40
  829.   mov ds,ax
  830.   mov wo [72],1234
  831.   jmp FFFF:0000
  832.  
  833.   u 100
  834.   q
  835.   .... end debug.in, cut here ....
  836. Give the following command
  837.   debug < debug.in
  838. You'll get
  839.   0E9E:0100 B84000        MOV     AX,0040
  840.   0E9E:0103 8ED8          MOV     DS,AX
  841.   0E9E:0105 C70672003412  MOV     WORD PTR [0072],1234
  842.   0E9E:010B EA0000FFFF    JMP     FFFF:0000
  843. This translates into
  844.     Inline ($B8/$40/$00/
  845.             $8E/$D8/
  846.             $C7/$06/$72/$00/$34/$12/
  847.             $EA/$00/$00/$FF/$FF);
  848. --------------------------------------------------------------------
  849.  
  850. From ts@uwasa.fi Sun Dec 26 00:00:51 1993
  851. Subject: Out of memory in compiling
  852.  
  853. 51. *****
  854.  Q: I am running out of memory when compiling my large program. What
  855.     can I do?
  856.  
  857.  A: If you are compiling your program from within the IDE (the
  858. Integrated Development Environment) then select the Option from the
  859. main menu, choose the Compiler item and set the Link buffer to
  860. Disk. (Also make the Compile option Destination to be Disk).
  861.    If this is not sufficient, next resort to using the TPC command
  862. line version of the Turbo Pascal compiler instead of the IDE.  Use
  863. the "Link buffer on disk" option.
  864.    Divide your program into units. It is advisable anyway for
  865. modularity when your program size grows.
  866.    If you have extended memory, instead of TURBO.EXE use TPX.EXE, if
  867. you have TP 7.0. If you are into protected mode programming then use
  868. Borland Pascal BP 7.0.
  869.  
  870.  A2: If you would prefer compiling your program from within the IDE
  871. but cannot do it for the above reason (or if you would prefer to
  872. compile your program from within your favorite editor instead of the
  873. TP IDE) you can use the following trick. If your editor has a macro
  874. language like most good editors do, the assign a hotkey macro that
  875. compiles the current file with the TPC. If you are using SemWare's
  876. QEdit editor you'll find such a macro in garbo.uwasa.fi:/pc/ts/
  877. tsqed17.zip ("Macros and configurations for QEdit text-editor").
  878.    Also your editor must be swapped to disk during the compilation
  879. if memory is critical. There is a very good program for doing that:
  880. /pc/sysutil/shroom2d.zip ("Shell Room, Swap to disk when shelling to
  881. application"). For example I invoke the QEdit editor with using the
  882. following batch:
  883.  c:\tools\shroom -s r:\cmand -z 1024 c:\qedit\q %1 %2 %3 %4 %5 %6 %7
  884. You'll find more about the switches in the Shell Room documentation.
  885. The -s switch designates the swap destination (my r:\cmand directory
  886. is on my ramdisk). The -z switch sets the shell environment size.
  887.   An unfortunate part is that the TP 5.0 Turbo Pascal IDE is about
  888. the only program I know that is not amenable the to Shell Room
  889. utility, so you cannot utilize Shell Room to swap the TP IDE to
  890. disk. Blessfully, at least TP 7.0 no more has this problem.
  891. --------------------------------------------------------------------
  892.  
  893. From ts@uwasa.fi Sun Dec 26 00:00:52 1993
  894. Subject: Last position write woes
  895.  
  896. 52. *****
  897.  Q: How do I avoid scrolling in the last column of the last row?
  898.  
  899.  A: If you use write or writeln at the last column of the last row
  900. (usually 80,25) the screen will scroll. If you wish to avoid the
  901. scrolling you'll have to use an alternative write that does not move
  902. the cursor. Here is a procedure to write without moving the cursor
  903.   uses Dos;
  904.   procedure WriteChar (Character : char; fgColor, bgColor : byte);
  905.   var r : registers;
  906.   begin
  907.     FillChar (r, SizeOf(r), 0);
  908.     r.ah := $09;
  909.     r.al := ord(Character);
  910.     r.bl := (bgColor shl 4) or fgColor;
  911.     r.cx := 1;    { Number of repeats }
  912.     Intr ($10, r);
  913.   end;  (* writechar *)
  914. Thus, if you wish to write to the last column of the last row, you
  915. must first move the cursor to that position. That can be done in
  916. alternative ways. One might get there by having written previously
  917. on the screen (with writeln and write routines) until one is in that
  918. position. Another alternative is using GoToXY(80,20), but then you
  919. have to use the Crt unit. If you don't want to use it, then you can
  920. move the cursor by employing "GOATXY As the ordinary GoToXY but no
  921. Crt unit required" from garbo.uwasa.fi:/pc/ts/ tspa*.zip.
  922.    There is an alternative interrupt service ($0A) which does the
  923. same as service $09, but uses the default colors instead. Just
  924. substitute $0A for $09, and leave the r.bl assignment out of the
  925. WriteChar routine.
  926.    Another option for writing anyhere on the screen without
  927. affecting the cursor is using direct screen writes:
  928.   uses Dos;
  929.   procedure WriteChar (c : char; x, y : byte; fg, bg : byte);
  930.   var vidstart : word;
  931.       regs     : registers;
  932.   begin
  933.     FillChar (regs, SizeOf(regs), 0);
  934.     regs.ah := $0F;
  935.     Intr ($10, regs);  { Color or MonoChrome video adapter }
  936.     if regs.al = 7 then vidstart := $B000 else vidstart := $B800;
  937.     mem[vidstart:((y-1)*80+x-1)*2] := ord(c);
  938.     mem[vidstart:((y-1)*80+x-1)*2+1] := (bg shl 4) or fg;
  939.   end;
  940. To write to the last position simply apply e.g.
  941.   WriteChar ('X', 80, 25, 14, 0);  { Yellow on black }
  942. The foreground (fg) and the background (bg) color codes are
  943.   Black        =   0
  944.   Blue         =   1
  945.   Green        =   2
  946.   Cyan         =   3
  947.   Red          =   4
  948.   Magenta      =   5
  949.   Brown        =   6
  950.   LightGray    =   7
  951.   DarkGray     =   8
  952.   LightBlue    =   9
  953.   LightGreen   =  10
  954.   LightCyan    =  11
  955.   LightRed     =  12
  956.   LightMagenta =  13
  957.   Yellow       =  14
  958.   White        =  15
  959.   Blink        = 128
  960. Yet another option is the following, but it needs the Crt unit. On
  961. the other hand, it uses the default color. This is quite a good and
  962. easy solution. I captured this fairly frequent idea from a posting
  963. by Robert Buergi (nbuero@hslrswi.hasler.ascom.ch).
  964.   uses Crt;
  965.   procedure WriteToCorner (c : char);
  966.   begin
  967.     Inc (WindMax);
  968.     GotoXY (80, 25);
  969.     write (c);
  970.     Dec (WindMax);
  971.   end;  (* writeToCorner *)
  972. --------------------------------------------------------------------
  973.  
  974. From ts@uwasa.fi Sun Dec 26 00:00:53 1993
  975. Subject: Hiding a directory
  976.  
  977. 53. *****
  978.  Q: How can one hide (or unhide) a directory using a TP program?
  979.  
  980.  A: Here is the code using interrupt programming. Incidentally,
  981. since MsDos 5.0 the attrib command can be used to hide and unhide
  982. directories.
  983. (* Hide a directory. Before using it would be prudent to check
  984.    that the directory exists, and that it is a directory.
  985.    With a contribution from Jan Nielsen jak@hdc.hha.dk
  986.    Based on information from Duncan (1986), p. 410 *)
  987. procedure HIDE (dirname : string);
  988. var regs : registers;
  989. begin
  990.   FillChar (regs, SizeOf(regs), 0);  { standard precaution }
  991.   dirname := dirname + #0;           { requires ASCII strings }
  992.   regs.ah := $43;                    { function }
  993.   regs.al := $01;                    { subfunction }
  994.   regs.ds := Seg(dirname[1]);        { point to the name }
  995.   regs.dx := Ofs(dirname[1]);
  996.   regs.cx := 2; { set bit 1 on }     { to unhide set regs.cx := 0 }
  997.   Intr ($21, regs);                  { call the interrupt }
  998.   if regs.Flags and FCarry <> 0 then { were we successful }
  999.     writeln ('Failed to hide');
  1000. end;  (* hide *)
  1001.  
  1002.  A2: An alternative method by Dr. Abimbola Olowofoyeku
  1003. laa12@seq1.keele.ac.uk. No paths.
  1004.   procedure HIDE (dirname : string);
  1005.   var FileInfo : searchRec;
  1006.       f        : file;
  1007.   begin
  1008.     FindFirst (dirname, Directory, FileInfo);
  1009.     while DosError = 0 do
  1010.       begin
  1011.         assign (f, FileInfo.Name);
  1012.         SetFAttr (f, Hidden);
  1013.         FindNext (FileInfo);
  1014.       end;
  1015.   end;  (* hide *)
  1016.   {}
  1017.   procedure UNHIDE (dirname : string);
  1018.   var FileInfo : searchRec;
  1019.       f        : file;
  1020.   begin
  1021.     FindFirst (dirname, AnyFile, FileInfo);
  1022.     while DosError = 0 do
  1023.       begin
  1024.         assign (f, FileInfo.Name);
  1025.         SetFAttr (f, Archive);
  1026.         FindNext (FileInfo);
  1027.       end;
  1028.   end;  (* unhide *)
  1029. --------------------------------------------------------------------
  1030.  
  1031. From ts@uwasa.fi Sun Dec 26 00:00:54 1993
  1032. Subject: Testing file opened status
  1033.  
  1034. 54. *****
  1035.  Q: How do I test whether a file is already open in a TP program?
  1036.  
  1037.  A: This question is best answered by providing the code:
  1038.   uses Dos;
  1039.   {... for non-text files ...}
  1040.   function ISFOPEN (var filePointer : file) : boolean;
  1041.   begin
  1042.     isfopen := FileRec(filePointer).mode <> FmClosed;
  1043.   end;
  1044.   {}
  1045.   {... for text files ...}
  1046.   function ISTOPEN (var filePointer : text) : boolean;
  1047.   begin
  1048.     istopen := TextRec(filePointer).mode <> FmClosed;
  1049.   end;
  1050.   {}
  1051.   procedure TEST;          { Testing a non-text file }
  1052.   const name = 'R:\TMP';
  1053.   var f  : file;
  1054.   begin
  1055.     Assign (f, name);
  1056.     writeln ('File ', name, ' is open is ', ISFOPEN(f));
  1057.     {$I-} rewrite (f); {$I+}
  1058.     if IOResult <> 0 then
  1059.       begin
  1060.         writeln ('Failed to open ', name);
  1061.         exit;
  1062.       end;
  1063.     writeln ('File ', name, ' is open is ', ISFOPEN(f));
  1064.     close(f);
  1065.     writeln ('File ', name, ' is open is ', ISFOPEN(f));
  1066.   end;
  1067. --------------------------------------------------------------------
  1068.  
  1069. From ts@uwasa.fi Sun Dec 26 00:00:55 1993
  1070. Subject: From string to real
  1071.  
  1072. 55. *****
  1073.  Q: How can I test and convert a numerical string into a real?
  1074.  
  1075.  A: An easy task in Turbo Pascal but in standard Pascal this
  1076. frequent task is much trickier. Here are both the versions for
  1077. general edification :-).
  1078.   (* Convert and test a numerical string with Turbo Pascal *)
  1079.   function DIGVALFN (mj : string; var ok : boolean) : real;
  1080.   var k : integer;
  1081.       x : real;
  1082.   begin
  1083.     Val (mj, x, k);
  1084.     ok := k = 0;
  1085.     if ok then digvalfn := x else digvalfn := 0;
  1086.   end;  (* digvalfn *)
  1087.   {}
  1088.   (* Convert and test a numerical string with standard Pascal routines only *)
  1089.   procedure DIGVAL (mj : string; var number : real; var ok : boolean);
  1090.   label 1;
  1091.   var il, lenl, pl, kl1, kl2 : integer;
  1092.       nrol                   : boolean;
  1093.       numberdl               : real;
  1094.   begin
  1095.     ok := true; lenl := Length (mj); nrol := false; pl := 0; number := 0.0;
  1096.     if lenl = 0 then ok := false;
  1097.     for il:=2 to lenl do if (mj[il]='-') or (mj[il]='+') then ok := false;
  1098.     for il:=1 to lenl do
  1099.       case mj[il] of
  1100.         '0'..'9','+','-','.' : ; else ok := false;
  1101.       end;
  1102.     for il:=1 to lenl do
  1103.       case mj[il] of '0'..'9' : begin nrol := true; goto 1; end; end;
  1104.     1: if nrol = false then ok := false;
  1105.     for il:=1 to lenl do if mj[il] = '.' then pl := pl + 1;
  1106.     if pl > 1 then ok := false;
  1107.     kl1:=1; kl2:=lenl+1; if (mj[1]='-') or (mj[1]='+') then kl1 := 2;
  1108.     for il:=1 to lenl do if mj[il] = '.' then kl2 := il;
  1109.     if kl2-kl1 > 38 then ok := false;
  1110.     if ok then
  1111.       begin
  1112.         number:=0; numberdl:=0;
  1113.         for il:=kl1 to kl2-1 do number := (ord(mj[il])-48)+10*number;
  1114.         if kl2 < lenl+1 then
  1115.           for il:=lenl downto kl2+1 do
  1116.             numberdl := (ord(mj[il])-48)/10+numberdl/10;
  1117.         number := number + numberdl;
  1118.         if mj[1]='-' then number := -number;
  1119.       end; {if ok}
  1120.   end;  (* digval *)
  1121.   {}
  1122.   procedure TEST;
  1123.   var s : string; r : real; ok : boolean;
  1124.   begin
  1125.     s := '123.41';
  1126.     r := DIGVALFN (s, ok);
  1127.     if ok then writeln (r) else writeln ('Error in ', s);
  1128.     DIGVAL (s, r, ok);
  1129.     if ok then writeln (r) else writeln ('Error in ', s);
  1130.   end;
  1131. --------------------------------------------------------------------
  1132.  
  1133. From ts@uwasa.fi Sun Dec 26 00:00:56 1993
  1134. Subject: Decompiling a TP .EXE
  1135.  
  1136. 56. *****
  1137.  Q: How can I reverse a TP .EXE or .TPU back into source code?
  1138.  
  1139.  A: This is simply asking too much. You cannot decompile a TP
  1140. program in a manner that would give you back the original source.
  1141. This method of reverse engineering is not on in actual practice.
  1142. Quoting Jeroen Pluimers (jeroenp@dragons.nest.nl) "During the
  1143. compilation, important information get's lost about variables,
  1144. types, identifiers etc. Writing a Pascal Decompiler is impossible.
  1145. The best you can achieve is a disassembler that can help you
  1146. recognize some Pascal statements."
  1147.    You might note that this question somewhat resembles another
  1148. frequent question "How can I convert a TPU unit of one TP version to
  1149. another?" which cannot be solved without the original source code.
  1150. --------------------------------------------------------------------
  1151.  
  1152. From ts@uwasa.fi Sun Dec 26 00:00:57 1993
  1153. Subject: Calculating date/time differences
  1154.  
  1155. 57. *****
  1156.  Q: How can I calculate the difference between two points of time?
  1157.  
  1158.  A: This is an unconfirmed answer so be a little careful with it.
  1159. But at the very least it shows some interesting information about
  1160. Turbo Pascal date/time conventions and how to declare and initialize
  1161. typed constants if they are records.
  1162.   program TimDifTest;
  1163.   uses Dos;
  1164.   const a : DateTime
  1165.           = (year:1992; month:10; day:24; hour:5; min:29; sec:38);
  1166.         b : DateTime
  1167.           = (year:1993; month:11; day:23; hour:6; min:30; sec:51);
  1168.   var aLong, bLong, cLong : longint;
  1169.       c : DateTime;
  1170.   begin
  1171.     PackTime (a, aLong);
  1172.     PackTime (b, bLong);
  1173.     cLong := bLong - aLong;
  1174.     UnpackTime (cLong, c);
  1175.     writeln (c.year-1980, ' ', c.month, ' ', c.day, ' ',
  1176.              c.hour, ' ', c.min, ' ', c.sec);
  1177.   end.
  1178. More generally than for dates between 1980 and 2079, or for more
  1179. accurate results, the difference between two date/times can be
  1180. calculated using Zeller's congruence (see the item "I want code that
  1181. gives the weekday of the given date"). First calculate Zeller's for
  1182. both the dates, convert them, and the hour, min, and sec into
  1183. seconds, subtract, and convert back.
  1184. --------------------------------------------------------------------
  1185.  
  1186. From ts@uwasa.fi Sun Dec 26 00:00:58 1993
  1187. Subject: Stand-alone or from IDE
  1188.  
  1189. 58. *****
  1190.  Q: Is a program running stand-alone or from within the IDE?
  1191.  
  1192.  A: Not all questions have an answer yet. I posed this question to
  1193. the UseNet newsgroup comp.lang.pascal, but we have not found an
  1194. answer that would be general for all MsDos versions. The closest we
  1195. have comes from dmurdoch@mast.queensu.ca Duncan Murdoch (naturally
  1196. :-). I have done some slight editing of Duncan's solution.
  1197.   uses Dos;
  1198.   type Pchar = ^Char;
  1199.   function Asciiz2Str (p : Pchar) : string;
  1200.   var
  1201.     result : string;
  1202.     len : byte;
  1203.   begin
  1204.     len := 0;
  1205.     while (p^ <> #0) and (len < 255) do
  1206.     begin
  1207.       inc(len);
  1208.       result[len] := p^;
  1209.       inc(longint(p));
  1210.     end;
  1211.     result[0] := chr(len);
  1212.     Asciiz2Str := result;
  1213.   end;
  1214.   {}
  1215.   var parentSeg : ^word;
  1216.       p         : pchar;
  1217.   begin
  1218.     if swap(DosVersion) < $0400 then
  1219.       writeln ('Requires Dos 4.0+')
  1220.     else begin
  1221.       parentSeg := ptr (prefixSeg, $16);
  1222.       p := ptr (ParentSeg^-1, 8);
  1223.       writeln ('I was launched by ', Asciiz2Str(p));
  1224.     end;
  1225.   end.
  1226. Another suggestion has been that the contents of ParamStr(0) would
  1227. show the launching program. I tested this on several configurations
  1228. and TP versions and found no evidence that the contention would
  1229. hold.
  1230. --------------------------------------------------------------------
  1231.  
  1232. From ts@uwasa.fi Sun Dec 26 00:00:59 1993
  1233. Subject: Memory Addressing
  1234.  
  1235. 59. *****
  1236.  Q: Please explain Turbo Pascal memory addressing to me.
  1237.  
  1238.  A: This is far from an easy question, but let's see what we can do.
  1239. The origins of the difficulties are in the design of the 8086 chip
  1240. which still restricts all Turbo Pascal applications (which contrary
  1241. to Borland Pascal use the original real mode). The 8086 (aka real
  1242. mode) addressing is based on 16-bit registers. As you probably know
  1243. 2^16 is 65536 which means that you cannot directly point to all
  1244. addresses of the lower and upper memory, which ranges from 0 to
  1245. 1048575 (2^20-1). Thus all the memory addresses are pointed to into
  1246. two parts in TP programs, the segment and the offset. The following
  1247. example of the PC's memory illustrates.
  1248.  
  1249.   Decimal  Hexa-
  1250.   address  decimal  Segment  Offset  What
  1251.         0   $00000    $0000   $0000  Conventional memory starts
  1252.      1043   $00413    $0040   $0013  Base memory in Kb, a word
  1253.    655359   $9FFFF    $9000   $FFFF  Conventional memory ends
  1254.    655360   $A0000    $A000   $0000  Upper memory begins
  1255.   1048575   $FFFFF    $F000   $FFFF  Upper memory ends
  1256.  
  1257. To exemplify, let's look at some alternative ways we could access
  1258. the information about the amount of the base memory. It is very
  1259. straight-forward, since in a PC that information is at the fixed
  1260. memory location show by the above table. We know this in advance.
  1261. Using direct memory accessing we could write
  1262.   var memsize : word;
  1263.   memsize := MemW [$0040:$0013];
  1264.   writeln (memsize);
  1265.   {.. or ..}
  1266.   var memsize : word absolute $0040:$0013;
  1267.   writeln (memsize);
  1268. If you are not familiar with the true meaning of pointers, they may
  1269. feel confusing, but what they basically are is just what the name
  1270. indicates, pointers to memory locations. Study the following
  1271. example.
  1272.   var memsizePtr : ^word;           { A pointer to a word }
  1273.   begin
  1274.     memsizePtr := ptr ($40, $13);   { Assign the pointer a value }
  1275.     writeln (memsizePtr^);          { Write what is in the address }
  1276.   end.                              { that was pointed to }
  1277. This was relatively simple, since we knew in advance the location of
  1278. the information. Lets look at a case where we do not know that.
  1279. Consider
  1280.   var x : word;
  1281.   begin
  1282.     x := 1223;
  1283.     writeln (x);
  1284.   end.
  1285. We have a variable x somewhere in the memory, and we can refer to it
  1286. without ever needing to know where the variable actually is in the
  1287. memory. But how does one find out if one for some reason wants or
  1288. needs to know?
  1289.   var x       : word;
  1290.       Segment : word;
  1291.       Offset  : word;
  1292.       y       : ^word;
  1293.   begin
  1294.     x := 1223;
  1295.     writeln (x);
  1296.     Segment := Seg(x);
  1297.     Offset  := Ofs(x);
  1298.     writeln ('Variable x is at $', HEXFN(Segment), ':$', HEXFN(Offset));
  1299.     {... one test to ensure that the value really is in there ...}
  1300.     writeln (MemW [Segment:Offset]);
  1301.     {... another test to demonstrate that the value really is in there ...}
  1302.     y := Addr(x);
  1303.     writeln (y^);
  1304.   end.
  1305. Next consider
  1306.   var xPtr    : ^word;
  1307.       Segment : word;
  1308.       Offset  : word;
  1309.       yPtr    : ^word;
  1310.   begin
  1311.     xPtr^ := 1223;
  1312.     writeln (xPtr^);
  1313.     Segment := Seg(xPtr^);
  1314.     Offset  := Ofs(xPtr^);
  1315.     writeln ('$', HEXFN(Segment), ':$', HEXFN(Offset));
  1316.     {... a test to ensure that the value really is in there ...}
  1317.     yPtr := Ptr (Segment, Offset);
  1318.     writeln (yPtr^);
  1319.   end.
  1320. A further aspect of pointers is that you can utilize them to put a
  1321. variables onto the heap instead of the data segment so that you
  1322. won't run so easily out of space.
  1323.   var xPtr : ^word;
  1324.   begin
  1325.     { Put it onto the heap }
  1326.     New (xPtr);
  1327.     xPtr^ := 1223;
  1328.     writeln (xPtr^);
  1329.     { Get rid of it }
  1330.     Dispose (xPtr); xPtr := nil;
  1331.     readln;
  1332.   end.
  1333. Let us return to the addressing. The formulas for converting between
  1334. the addresses (sent in by Duncan Murdoch) are
  1335.   Physical := longint(segment)*16 + offset;
  1336.   {}
  1337.   Segment  := Physical div 16;
  1338.   Offset   := Physical mod 16; { This gives the normalized form }
  1339. There are multiple Segment:Offset pairs that refer to the same
  1340. address, e.g. $0000:$0413 and $0040:$0013. The normalized addresses,
  1341. with the offset in the range of 0 to $F, are, however, unique. An
  1342. example $0041:$0003.
  1343. --------------------------------------------------------------------
  1344.  
  1345. From ts@uwasa.fi Sun Dec 26 00:00:60 1993
  1346. Subject: Getting a bit from a byte
  1347.  
  1348. 60. *****
  1349.  Q: How do I obtain a bit or bits from a byte, a word or a longint?
  1350.  
  1351.  A: For bit operations think of the variable as a binary number
  1352. instead of a decimal. Consider for example
  1353.   var x : word;
  1354.   x := 219;
  1355. In binary presentation it is
  1356.   The word                  0000 0000 1101 1011
  1357.   Position in the word      FEDC BA98 7654 3210
  1358.  
  1359. Say you need the value of bit 6 (the seventh bit) in the word. You
  1360. can "and" the following words
  1361.   0000 0000 1101 1011    (219)
  1362.   0000 0000 0100 0000    ( 64)
  1363. In decimal TP notation this amounts to
  1364.   var b : word;
  1365.   b := x and 64;
  1366. The value of b is now
  1367.   0000 0000 0100 0000    ( 64)
  1368. To get the bit value (0 or 1) you need to shift the result right by
  1369. six steps, that this the expression becomes the often seen but
  1370. cryptic
  1371.   b := (x and 64) shr 6;
  1372. which means that the value of b is finally 1 in this example.
  1373.  
  1374. Ok, but what then if you need the combined value of bits six and
  1375. seven. The answer is evident if you consider the binary presentation
  1376.   0000 0000 1101 1011    (219)
  1377.   0000 0000 1100 0000    (192)
  1378. hence
  1379.   b := (x and 192) shr 6;
  1380. which will give 3 as it should.
  1381.  
  1382. So far, so good. What if you need to turn on bit nine in a word
  1383. without interfering with the other bits. The binary presentation,
  1384. again, is the key. You'll have to "or" the following
  1385.   0000 0000 1101 1011    (219)
  1386.   0000 0010 0000 0000    (512)
  1387. that is
  1388.   x := x or 512;
  1389. This results to
  1390.   0000 0010 1101 1011    (731)
  1391.  
  1392. What if you wish to turn off, say bit 6, in
  1393.   0000 0000 1101 1011    (219)
  1394.   1111 1111 1011 1111  (65471)
  1395. This is achieved by
  1396.   x := 219;
  1397.   x := x and 65471;
  1398. This results to
  1399.   0000 0000 1001 1011    (155)
  1400.  
  1401. Consider the following application as an example. The number of a
  1402. PC's floppy disk drives (minus one) is stored in bits 6 and 7 in a
  1403. word returned by interrupt $11. This is the code to find out how
  1404. many disk drives a PC has.
  1405.   uses Dos;
  1406.   function NrOfFDiskDrives : byte;
  1407.   var regs : registers;
  1408.   begin
  1409.     Intr ($11, regs);
  1410.     NrOfFDiskDrives := ((regs.ax and 192) shr 6) + 1;
  1411.   end;
  1412.  
  1413. A tip from Duncan Murdoch.  You might wish to predefine the
  1414. following constants for easier handling
  1415.   const bit0  = 1;
  1416.         bit2  = 2;
  1417.         bit3  = 4;
  1418.         :
  1419.         bit31 = 32768;
  1420.  
  1421. Finally, you also might want to look at the item "Getting a nybble
  1422. from a byte".
  1423. --------------------------------------------------------------------
  1424.